package com.tust.controller;

import com.tust.domain.*;
import com.tust.paging.UserPaging;
import com.tust.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/*控制层Controller用户类*/
@Controller
public class UserController {
    /*自动注入Service用户接口*/
    @Autowired
    private UserService userService;
    /*自动注入Service消息接口*/
    @Autowired
    private MessageService messageService;
    /*自动注入Service贴文接口*/
    @Autowired
    private ArticleService articleService;
    /*自动注入Service点赞接口*/
    @Autowired
    private FavorService favorService;
    /*自动注入Service收藏接口*/
    @Autowired
    private CollectionService collectionService;

    /********************************************管理端请求********************************************/

    /*用于分页功能*/
    private List<User> selectUsers = null;//存储完整查询结果
    private UserPaging userPaging = new UserPaging();//分页类

    /**
     * 查询所有用户
     * 响应"/selectAllUser.do"请求
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/selectAllUser.do")
    public List<User> selectAllUser() {
        List<User> users = userService.selectAllUser();

        selectUsers = users;//存储完整查询结果
        userPaging.recordCount = selectUsers.size();
        userPaging.pageCount = selectUsers.size() % userPaging.maxRecordNum == 0 ? selectUsers.size() / userPaging.maxRecordNum : selectUsers.size() / userPaging.maxRecordNum + 1;
        userPaging.currentPage = 0;//当前页码为0

        System.out.println("查询所有用户: size:" + users.size());
        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 查询用户
     * 响应"/selectUser.do"请求
     * @param selectOption 选择项
     * @param selectContent 选择内容
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/selectUser.do")
    public List<User> selectUser(String selectOption, String selectContent) {
        List<User> users = null;

        if (selectOption.equals("用户ID")) users = userService.selectUserByUID(Integer.valueOf(selectContent));//按用户ID查找用户记录
        else if (selectOption.equals("用户名")) users = userService.selectUserByUname(selectContent);//按用户名查找用户记录
        else if (selectOption.equals("禁言等级")) users = userService.selectUserByUbanLevel(Integer.valueOf(selectContent));//按用户禁言等级查找用户记录

        selectUsers = users;//存储完整查询结果
        userPaging.recordCount = selectUsers.size();
        userPaging.pageCount = selectUsers.size() % userPaging.maxRecordNum == 0 ? selectUsers.size() / userPaging.maxRecordNum : selectUsers.size() / userPaging.maxRecordNum + 1;
        userPaging.currentPage = 0;//当前页码为0

        System.out.println("查询用户: selectOption:" + selectOption + " selectContent:" + selectContent + " size:" + users.size());
        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 分页上一页
     * 响应"/preUserPage.do"请求
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/preUserPage.do")
    public List<User> preUserPage() {
        if (!userPaging.isFirstPage()) {//当前页不是第一页
            userPaging.currentPage--;//当前页码-1
        }
        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 分页下一页
     * 响应"/nextUserPage.do"请求
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/nextUserPage.do")
    public List<User> nextUserPage() {
        if (!userPaging.isLastPage(selectUsers)) {//当前页不是最后一页
            userPaging.currentPage++;//当前页码+1
        }
        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 分页最前页
     * 响应"/topUserPage.do"请求
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/topUserPage.do")
    public List<User> topUserPage() {
        userPaging.currentPage = 0;//当前页码为0
        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 分页最尾页
     * 响应"/endUserPage.do"请求
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/endUserPage.do")
    public List<User> endUserPage() {
        userPaging.currentPage = userPaging.pageCount - 1;//当前页码为总分页数量-1
        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 获取当前分页信息
     * 响应"/getUserPageInfo.do"请求
     * @return pageInfo 返回分页信息
     */
    @ResponseBody
    @RequestMapping("/manage/getUserPageInfo.do")
    public UserPaging getUserPageInfo() {
        return userPaging;
    }

    /**
     * 禁言用户
     * 响应"/banUserTalk.do"请求
     * @param UID 用户ID
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/manage/banUserTalk.do")
    public String banUserTalk(int UID) {
        String msg = null;
        Message message = new Message();

        //当前时间+1天
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        Date date = new Date();//获取当前时间
        calendar.setTime(date);
        calendar.add(calendar.DATE,1);//当前时间+1天
        date=calendar.getTime();

        if (userService.updateUserBan(UID, -1, formatter.format(date)) == 1) {//禁言成功
            msg = "banUserSuccess";

            //发送消息
            message.setMsgReceiver(UID);
            message.setArtID(-1);
            message.setMsgContent("非常抱歉，您已被管理员禁言1天");
            date = new Date();//获取当前时间
            message.setMsgTime(formatter.format(date));
            message.setMsgFromUser(0);
            message.setMsgIsReaded(0);
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else {//禁言失败
            msg = "banUserFalse";
        }

        System.out.println("禁言用户: " + msg);
        return msg;
    }

    /**
     * 解除禁言用户
     * 响应"/allowUserTalk.do"请求
     * @param UID 用户ID
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/manage/allowUserTalk.do")
    public String allowUserTalk(int UID) {
        String msg = null;
        Message message = new Message();

        if (userService.updateUserBan(UID, 0, null) == 1) {//解除禁言成功
            msg = "allowUserSuccess";

            //发送消息
            message.setMsgReceiver(UID);
            message.setArtID(-1);
            message.setMsgContent("您已被管理员解除禁言");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();//获取当前时间
            message.setMsgTime(formatter.format(date));
            message.setMsgFromUser(0);
            message.setMsgIsReaded(0);
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else {//解除禁言失败
            msg = "allowUserFalse";
        }

        System.out.println("解除禁言用户: " + msg);
        return msg;
    }

    /**
     * 刷新页面
     * 响应"/refreshUser.do"请求
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/refreshUser.do")
    public List<User> refreshUser() {
        //禁言操作后需要存储新的完整查询结果
        List<User> users = userService.selectAllUser();
        selectUsers = users;//存储完整查询结果
        userPaging.recordCount = selectUsers.size();
        userPaging.pageCount = selectUsers.size() % userPaging.maxRecordNum == 0 ? selectUsers.size() / userPaging.maxRecordNum : selectUsers.size() / userPaging.maxRecordNum + 1;

        return userPaging.showPageContent(selectUsers);//调用分页显示方法
    }

    /**
     * 查询用户
     * 响应"/selectUname.do"请求
     * @param UID 用户ID
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/manage/selectUname.do")
    public List<User> selectUname(int UID) {
        List<User> users = userService.selectUserByUID(UID);//按用户ID查找用户记录
        System.out.println("查询用户姓名: size:" + users.size());
        return users;
    }

    /********************************************客户端请求********************************************/

    /**
     * 用户登录
     * 响应"/userLogin.do"请求
     * @param Uname 用户名
     * @param Upasswd 用户密码
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/userLogin.do")
    public String userLogin(String Uname, String Upasswd) {
        String msg = null;

        List<User> users = userService.selectUserByUname(Uname);//按用户名查找用户记录
        if (users.size() == 1) {//用户存在
            msg = "passwordFalse";//密码错误
            if (users.get(0).getUpasswd().equals(Upasswd)) msg = "loginSuccess";//登录成功
        } else {//用户不存在
            msg = "userNotExist";
        }

        System.out.println("用户登录: " + msg);
        return msg;
    }

    /**
     * 用户注册
     * 响应"/userRegister.do"请求
     * @param Uname 用户名
     * @param Upasswd 用户密码
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/userRegister.do")
    public String userRegister(String Uname, String Upasswd) {
        String msg = null;

        List<User> users = userService.selectUserByUname(Uname);//按用户名查找用户记录
        if (users.size() > 0) msg = "userExist";//用户已存在
        else {
            //插入新用户
            User user = new User();
            user.setUname(Uname);
            user.setUpasswd(Upasswd);

            if (userService.insertUser(user) == 1) msg = "registerSuccess";//注册成功
            else msg = "registerFalse";//注册失败
        }
        
        System.out.println("用户注册: " + msg);
        return msg;
    }

    /**
     * 获取用户信息
     * 响应"/getUserInfo.do"请求
     * @param Uname 用户名
     * @return List<User> 返回用户集合
     */
    @ResponseBody
    @RequestMapping("/getUserInfo.do")
    public List<User> getUserInfo(String Uname) {
        List<User> users = userService.selectUserByUname(Uname);//按用户名查找用户记录
        System.out.println("获取用户信息: size:" + users.size());
        return users;
    }

    /**
     * 获取用户点赞量
     * 响应"/getUfavorNum.do"请求
     * @param UID 用户ID
     * @return UfavorNum 返回用户点赞数
     */
    @ResponseBody
    @RequestMapping("/getUfavorNum.do")
    public int getUfavorNum(int UID) {
        int UfavorNum = 0;

        List<Article> articles = articleService.selectArticleByUID(UID);//按用户ID查找贴文记录
        for (int i = 0; i < articles.size(); i++) UfavorNum += articles.get(i).getArtFavorNum();

        System.out.println("获取用户点赞量: " + UfavorNum);
        return UfavorNum;
    }

    /**
     * 获取用户收藏量
     * 响应"/getUcollNum.do"请求
     * @param UID 用户ID
     * @return UfavorNum 返回用户点赞数
     */
    @ResponseBody
    @RequestMapping("/getUcollNum.do")
    public int getUcollNum(int UID) {
        int UcollNum = 0;

        List<Article> articles = articleService.selectArticleByUID(UID);//按用户ID查找贴文记录
        for (int i = 0; i < articles.size(); i++) UcollNum += articles.get(i).getArtCollNum();

        System.out.println("获取用户收藏量：" + UcollNum);
        return UcollNum;
    }

    /**
     * 修改用户信息
     * 响应"/setUserInfo.do"请求
     * @param UID 用户ID
     * @param Uname 用户名
     * @param Upasswd 用户密码
     * @param Ugender 用户性别
     * @param Uint 用户简介
     * @param UfavorPrivacy 用户点赞隐私
     * @param UcollPrivacy 用户收藏隐私
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/setUserInfo.do")
    public String setUserInfo(int UID, String Uname, String Upasswd, String Ugender, String Uint, int UfavorPrivacy, int UcollPrivacy) {
        String msg = null;
        Message message = new Message();

        List<User> users = userService.selectUserByUname(Uname);//按用户名查找用户记录
        if (users.size() > 0 && !users.get(0).getUname().equals(Uname)) msg = "userExist";//用户已存在
        else if (userService.updateUserByUID(UID, Uname, Upasswd, Ugender, Uint, UfavorPrivacy, UcollPrivacy) == 1) {//修改用户信息成功
            msg = "updateUserSuccess";

            //发送消息
            message.setMsgReceiver(UID);
            message.setArtID(-1);
            message.setMsgContent("您的个人信息已被修改成功");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();//获取当前时间
            message.setMsgTime(formatter.format(date));
            message.setMsgFromUser(0);
            message.setMsgIsReaded(0);
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else {//修改用户信息失败
            msg = "updateUserFalse";
        }

        System.out.println("修改用户信息：" + msg);
        return msg;
    }

    /**
     * 更新用户禁言状态
     * 响应"/updateUbanStatus.do"请求
     * @param Uname 用户名
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/updateUbanStatus.do")
    public String updateUbanStatus(String Uname) {
        String msg = null;
        Message message = new Message();

        List<User> users = userService.selectUserByUname(Uname);//按用户名查找用户记录
        if (users.get(0).getUbanLevel() != -1) msg = "userNotBan";//用户未被禁言
        else{//用户被禁言
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();//获取当前时间
            Date UbanDate = null;
            try {
                 UbanDate = formatter.parse(users.get(0).getUbanTime());//获取用户禁言时间
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            if (date.after(UbanDate)) {//禁言时间已到
                if (userService.updateUserBan(users.get(0).getUID(), 0, null) == 1) {//更新用户禁言状态成功
                    msg = "updateUbanSuccess";

                    //发送消息
                    message.setMsgReceiver(users.get(0).getUID());
                    message.setArtID(-1);
                    message.setMsgContent("您的禁言状态已结束");
                    message.setMsgTime(formatter.format(date));
                    message.setMsgFromUser(0);
                    message.setMsgIsReaded(0);
                    if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
                } else {//更新用户禁言状态失败
                    msg = "updateUbanFalse";
                }
            } else {//禁言时间未到
                msg = "userBaning";
            }
        }

        System.out.println("更新用户禁言状态：" + msg);
        return msg;
    }
}
